cli script /Common/create_ha_trust {
proc script::init {} {
}

proc usage {} {
    puts "Create an HA trust relationship between this BIG-IP and another and synchronize this BIG-IP's configuration to the peer."
    puts "Options:"
    puts "  -h  hostname          Mandatory. (case sensitive) This is or will become the peer hostname in the configuration."
    puts "  -a  peer IP address   Optional, unless checking trust only.  Must be reachable."
    puts "  -u  username          Optional, unless checking trust only.  For an administrative user on the peer."
    puts "  -p  password          Optional, unless checking trust only.  "
}

proc script::run {} {
    if {![getopt tmsh::argv -h peer_hostname]} { usage; exit 1 }

    set trust_exists [check_trust_with_host $peer_hostname]

    if {$trust_exists} {
        puts "There is a trust with ${peer_hostname}."
    } else {
        puts "No trust exists with ${peer_hostname}."
        if {![getopt tmsh::argv -a peer_addr]}     { usage; exit 1 }
        if {![getopt tmsh::argv -u username]}      { usage; exit 1 }
        if {![getopt tmsh::argv -p password]}      { usage; exit 1 }
        puts "Creating trust relationship with ${peer_hostname} at ${peer_addr}."
        make_trust $peer_hostname $peer_addr $username $password



    }
}

proc check_trust_with_host {hostname} {
    puts "Checking for HA trust with ${hostname}."
    return [regexp $hostname [tmsh::list / cm trust-domain Root ca-devices]]
}

proc make_trust {hostname addr username password} {
    tmsh::modify /cm trust-domain /Common/Root ca-devices add \{ $addr \} name $hostname username admin password tusecure
}

proc getopt {_argv name {_var ""} {default ""}} {
upvar 1 $_argv argv $_var var
set pos [lsearch -regexp $argv ^$name]
if {$pos>=0} {
     set to $pos
     if {$_var ne ""} {
         set var [lindex $argv [incr to]]
     }
     set argv [lreplace $argv $pos $to]
     return 1
} else {
     if {[llength [info level 0]] == 5} {set var $default}
     return 0
}
}
proc script::help {} {
}

proc script::tabc {} {
}
}
